package com.alibaba.nacos.core.remote;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.PushCallBack;
import com.alibaba.nacos.api.remote.RequestCallBack;
import com.alibaba.nacos.api.remote.request.ServerRequest;
import com.alibaba.nacos.api.remote.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;

@Service
@Slf4j
public class RpcPushService {

    @Autowired
    private ConnectionManager connectionManager;

    public void pushWithoutAck(String connectionId,
                               ServerRequest request) {
        Connection connection = connectionManager.getConnection(connectionId);
        if (connection == null) {
            return;
        }

        try {
            connection.request(request, 3000L);
        } catch (Exception e) {
            log.error("pushWithoutAck <UNK>", e);
        }
    }

    public void pushWithCallback(String connectionId,
                                 ServerRequest request,
                                 PushCallBack requestCallBack,
                                 Executor executor) {

        Connection connection = connectionManager.getConnection(connectionId);
        if (connection == null) {
            requestCallBack.onSuccess();
            return;
        }

        try {
            connection.asyncRequest(request, new RequestCallBack() {
                @Override
                public void onResponse(Response response) {
                    if (response.isSuccess()) {
                        requestCallBack.onSuccess();
                    } else {
                        requestCallBack.onFail(new NacosException(response.getErrorCode(), response.getMessage()));
                    }
                }

                @Override
                public void onException(Throwable e) {
                    requestCallBack.onFail(e);
                }
            });
        } catch (Exception e) {
            log.error("com.alibaba.nacos.core.remote.RpcPushService.pushWithCallback error", e);
        }
    }
}
